﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HJ212_Common;
using HJ212_Protocol;
using SailHero.Soft.ESB.Communication.ClientAndServer.Client;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.EndPoints.Tcp;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.Messages;
using System.Configuration;
namespace HJT212_Protocol_HostClient
{
    public partial class ClientForm : Form
    {
        #region 构造函数
        public ClientForm()
        {
            InitializeComponent();
            this.lstBoxClients.DisplayMember = "Value";
            this.lstBoxClients.ValueMember = "Key";
        }
        #endregion

        #region 属性字段
        private IClient client;
        private Dictionary<string, string> ClntDics = new Dictionary<string, string>();
        #endregion

        #region 事件
        private void btnConn_Click(object sender, EventArgs e)
        {
            try
            {
                this.txtBoxContent.Text = "";
                string _port = ConfigurationManager.AppSettings["SrvPort"];
                client = ClientFactory.CreateClient(new ESBTcpEndPoint("127.0.0.1", Convert.ToInt32(_port)));
                client.MessageReceived += Client_MessageReceived;
                client.WireProtocol = new MyWireProtocol(); //Set custom wire protocol!
                client.MN = ConfigurationManager.AppSettings["MN"];
                client.PW = ConfigurationManager.AppSettings["PW"];
                client.Connect();
                
                btnSend.Enabled = true;
                string msg = "已经正确连接了服务端";
                this.txtBoxContent.AppendText(msg);
                txtBoxContent.Select(0, msg.Length);
                txtBoxContent.SelectionColor = Color.Black;
                this.btnConn.Enabled = false;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.lstBoxClients.SelectedItem == null)
                {
                    MessageBox.Show("请选接收机");
                    return;
                }

                string Code = string.Format("{0}", ReflectionUtil.GetProperty(this.lstBoxClients.SelectedItem, "Key"));
                string Name = string.Format("{0}", ReflectionUtil.GetProperty(this.lstBoxClients.SelectedItem, "Value"));
                string SendMsg = this.txtMsgToSend.Text.Trim();


                if (string.IsNullOrEmpty(SendMsg))
                {
                    MessageBox.Show("填写发送的消息");
                    return;
                }


                string str = this.txtMsgToSend.Text;
                TextMessage Tmsg = new TextMessage(str);
                Tmsg.FromMN = string.Format("{0}{1}", client.MN, "");
                Tmsg.To = Code + Name;
                client.SendMessage(Tmsg);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            //Client only accepts text messages 

            if (e.Message is TextMessage)
            {
                var message = e.Message as TextMessage;
                if (message == null)
                {
                    return;
                }
                string msg = message.Text;

                Delegate ddd = new Action<string>(delegate(string str)
                                                      {
                                                          this.txtBoxContent.AppendText(str + "\r\n");
                                                          txtBoxContent.Select(
                                                              this.txtBoxContent.Text.Length - str.Length, str.Length);
                                                          txtBoxContent.SelectionColor = Color.Red;
                                                      });
                this.BeginInvoke(ddd, msg);
            }
            else if (e.Message is ListMessage)
            {
                ShowClients((ListMessage)e.Message);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            client.Disconnect(); //Close connection to server
            client.Dispose();
            client = null;
            base.OnClosing(e);
        }
        #endregion

        #region 方法
        /// <summary>
        /// 显示客户端列表数据至列表控件
        /// </summary>
        /// <param name="ListMsg">客户端列表</param>
        private void ShowClients(ListMessage ListMsg)
        {

            try
            {

                Delegate ddd = new
                    Action<string>(
                    delegate(string lst)
                    {

                        string ClntListStr = lst;
                        ClntDics.Clear();
                        this.lstBoxClients.Items.Clear();
                        if (string.IsNullOrEmpty(ClntListStr))
                        {
                            return;
                        }
                        int totalLength = 0;
                        while (totalLength <= ClntListStr.Length - 60)
                        {

                            string code = ClntListStr.Substring(totalLength, 10);
                            string Name = ClntListStr.Substring(totalLength + 10, 50).Trim();
                            ClntDics.Add(code, Name);
                            this.lstBoxClients.Items.Add(new { Key = code, Value = Name });
                            totalLength += 60;

                        }

                    });
                this.BeginInvoke(ddd, ListMsg.Text);
            }
            catch (Exception ex)
            {

                throw;
            }
        }
        #endregion
    }
}
